package com.hxd.mall.module.product.home

import android.graphics.Color
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectFragment
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_isload_baichuan
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.TB_auther_isgo
import com.hxd.mall.constant.HxdConstantsRouterPath.Common.path_to_webview
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_login_input_phone
import com.hxd.mall.constant.HxdConstantsRouterPath.Search.path_product_search
import com.hxd.mall.constant.HxdGlobalInfo.instance
import com.hxd.mall.module.EventBean
import com.hxd.mall.module.MainActivity
import com.hxd.mall.module.common.AutherBean
import com.hxd.mall.module.product.home.active.HomeActiveTypeListAdapter
import com.hxd.mall.module.product.home.bean.*
import com.hxd.mall.module.usercenter.fragment.HomeTypeFragmentAdapter
import com.hxd.mall.module.usercenter.home.MineReLoadBean
import com.hxd.mall.utils.local.*
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.open.*
import com.hxd.threelibrary.baichuan.AlibcClient
import kotlinx.android.synthetic.main.fragment_home_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * @author zhaoyong
 * @description: 首页
 * @date :2019-07-19 18:41
 */
class HomeFragment : BaseInjectFragment<IHomePresenter>(), IHomeView {

    private var ext: ColorBean? = null
    private var mHomeBean: HomeTypeBean? = null
    private var userSession: UserSession? = null
    private val typeDownAdapter = HomeActiveTypeListAdapter(0, false, Color.WHITE, ContextCompat.getDrawable(instance, R.drawable.home_type_bottom_line))

    override fun attachLayoutRes(): Int = R.layout.fragment_home_layout

    override fun initViews() {
        EventBus.getDefault().register(this)

        addSetOnClickListener(authority, search, is_login) {
            onClick(it)
        }
    }

    override fun onResume() {
        super.onResume()
        if (mHomeBean == null || mHomeBean?.data == null)
            mPresenter?.getData(true)
    }

    override fun netHomeData(t: HomeTypeBean) {
        mHomeBean = t

        buildPagerIndicator(t.data)

        showPopuDialog(t.data?.popoverLayout)
        (activity as MainActivity).run {
            showPopoverDialog(t.data?.popupLayout)
        }

        mHomeBean?.data?.userSession?.run {
            AuthenSate(this)
        }
    }

    //icon弹窗布局
    private fun showPopuDialog(popupLayout: DataLayout?) {
        val popoList = popupLayout?.resources ?: mutableListOf()
        if (popoList.isNotEmpty()) {
            val resource = popoList[0]
            val show = resource.ext?.isShow ?: false
            if (show) {
                layout_popu.visibility = View.VISIBLE
                iv_popu_piv.setOnClickListener {
                    val path = "http://mall-h5-test.hxvc.com/mainActivity"
//                    routerNavigation(path_to_webview, key_web_url, resource.entryUri ?: "")
                    routerNavigation(path_to_webview, key_web_url, path)
                }
                iv_popu_piv.load(resource.pictUri, R.mipmap.product_item_icon, R.mipmap.product_item_icon, 0)
                iv_popu_close.setOnClickListener {
                    layout_popu.visibility = View.GONE
                }
            }
        }
    }

    private fun buildPagerIndicator(data: Data?) {
        //导航栏数据
        val list = data?.navigationLayout?.resources ?: mutableListOf()
        view_pager.offscreenPageLimit = list.size
        view_pager.adapter = HomeTypeFragmentAdapter(activity?.supportFragmentManager!!, data)
        addOnPageChangeListener(view_pager) {
            val oldIndex = typeDownAdapter.index

            (activity as MainActivity).current = it

            if (it == typeDownAdapter.index)
                return@addOnPageChangeListener

            changeItemColor(it)

            changeItem(oldIndex, it)

            typeDownAdapter.index = it
            typeDownAdapter.notifyItemChanged(oldIndex)
            typeDownAdapter.notifyItemChanged(it)
        }

        //商品类型
        recycler_productType.initRecyclerView(typeDownAdapter, orientation = RecyclerView.HORIZONTAL)
        setTypeList(list)
    }

    private fun changeItemColor(index: Int) {
        //这里只处理非首页，则直接将背景还原（如果是首页，则由首页banner通知切换）
        val colorBean = ColorBean(
            Color.WHITE,
            Color.parseColor("#FFDB3533"),
            ContextCompat.getDrawable(activity!!, R.drawable.shape_gray_bg_rectangle)!!,
            ContextCompat.getDrawable(activity!!, R.drawable.home_type_bottom_red_line)!!
        )
        if (index != 0) {
            changeColor(colorBean)
        } else {
            changeColor(ext ?: colorBean)
        }
    }

    private fun setTypeList(resources: List<Resource>) {
        typeDownAdapter.setNewData(resources)
        setAdapterListener(typeDownAdapter) { position ->
            changeItem(typeDownAdapter.index, position)

            view_pager.postDelayed({
                view_pager.currentItem = position

                changeItemColor(position)

            }, 100)
        }
    }

    private fun changeItem(oldIndex: Int, position: Int) {
        if (oldIndex != position) {
            //向右滑
            if (oldIndex < position) {
                val index = if ((position + 2) >= typeDownAdapter.data.size) typeDownAdapter.data.size - 1 else position + 2
                recycler_productType.scrollToPosition(index)
            } else {
                //向左滑
                val index = if ((position - 2) >= 0) position - 2 else 0
                recycler_productType.scrollToPosition(index)
            }
        }
    }

    //点击事件
    private fun onClick(it: View) {
        when (it) {
            authority -> ActivityUtil.jump {
                activity?.sendPoint(home_page_tb_authorization_button_click)
                //如果没有登录 需要先登录，登录完成后 调用接口
                if (userSession?.isTbAuthed == false) {
                    //初始化和打开SDK时由于时间太长，因此先显示一个loading
                    //showLoading()
                    taoBaoAuther(AutherBean(false, 0))
                }
            }
            is_login -> {
                activity?.sendPoint(home_page_log_in_button_click)
                routerNavigation(path_login_input_phone)
            }
            search -> {
                routerNavigation(path_product_search)
                activity?.sendPoint(search_box_click)
            }
        }
    }

    override fun initData() {
    }

    //获取淘宝地址URL
    override fun getTbAutehrUrl(t: TbAutherBean?) {
        if (null == t) {
            hideLoading()
            return
        }
        if (t.code == 0) {
            t.data?.authorizeUrl?.let {
                Log.i("taUrl", it + "")
                routerNavigation(path_to_webview, mutableMapOf(key_web_url to it, key_isload_baichuan to true))
            }
        } else {
            ToastUtil.showToast(t.msg.toString())
        }
    }

    //离开界面时关闭正在展示的loading
    override fun onStop() {
        super.onStop()
        hideLoading()
    }

    @Subscribe
    fun taoBaoAuther(event: AutherBean) {
        when (event.type) {
            -1 -> if (event.result == true) {
                author_layout.visibility = View.GONE
            } else {
                author_layout.visibility = View.VISIBLE
            }
            /**
             * 首页
             * 淘宝授权方法
             * @param event  为""时显示 dialog，
             * 其他界面发生eventbus时需要传递一个字符串值
             */
            0 -> {
                //初始化和打开SDK时由于时间太长，因此先显示一个loading
                if (!TB_auther_isgo) {
                    ToastUtil.showToast("授权太频繁啦，休息一会儿再试吧")
                    return
                }
                showLoading()
                AlibcClient.login { _, flag ->
                    if (!flag) {
                        TB_auther_isgo = flag
                        hideLoading()
                    }
                    mPresenter?.uploadTaoBaoInfo()
                }
            }
        }
    }

    /**
     * 子页请求完数据后更新状态
     */
//    @Subscribe
    fun AuthenSate(userSession: UserSession) {
        this.userSession = userSession
        //如果没有授权 则需要展示授权浮层布局
        userSession.let {
            if (!it.isLogin) {
                is_login.visibility = View.VISIBLE
                author_layout.visibility = View.GONE
            } else {
                if (!it.isTbAuthed) {
                    is_login.visibility = View.GONE
                    author_layout.visibility = View.VISIBLE
                } else {
                    author_layout.visibility = View.GONE
                    is_login.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 登录成功消息
     */
    @Subscribe
    fun loginSuccess(event: MineReLoadBean) {
        mPresenter?.getData(false)
    }

    /**
     * 退出成功接收消息
     */
    @Subscribe
    fun logoutSuccess(event: EventBean) {
        if (event.index == 0) {
            is_login.visibility = View.VISIBLE
            author_layout.visibility = View.GONE
        }
    }

    @Subscribe
    fun changeColor(ext: ColorBean) {
        Log.d("HomeFragment", view_pager.currentItem.toString())

        if (view_pager.currentItem == 0)
            this.ext = ext
        try {
            setColor(ext)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setColor(ext: ColorBean?) {
        if (ext == null)
            return
        //修改顶部区域的背景色
        view_home_top_bg.setBackgroundColor(ext.topbg)
        search.background = ext.searchBg

        typeDownAdapter.color = ext.tabTextColor
        typeDownAdapter.drawable = ext.lineBg
        typeDownAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}
